<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:replace="fragment/head"/>
    <!-- BEGIN Page level plugins -->
    <link href="resources/assets/global/plugins/datatables/datatables.min.css" rel="stylesheet"/>
    <link href="resources/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css"
          rel="stylesheet"/>
    <link href="resources/assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css"
          rel="stylesheet"/>
</head>

<body class="page-header-fixed page-sidebar-closed-hide-logo page-container-bg-solid page-content-white page-sidebar-closed">
<th:block th:with="
    ERPConstants = ${T(com.sh.caryr.erp.util.ERPConstants)} ,
    authTarget = ${ERPConstants.AUTH_TARGET_TRADE} ,
    createAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_CREATE},
    deleteAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_DELETE},
    updateAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_UPDATE},
    exportAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_EXPORT},
    importAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_IMPORT},
    submitAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_SUBMIT},
    packingAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_PACKING},
    deliverAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_DELIVER},
    signoffAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_SIGNOFF},
    settleAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_SETTLE},
    closeAuth = ${authTarget + '_' + ERPConstants.AUTH_ACTVT_CLOSE}
">
    <!-- BEGIN HEADER INNER -->
    <th:block th:replace="fragment/header"/>
    <!-- BEGIN CONTAINER -->
    <div class="page-container">
        <!-- BEGIN SIDEBAR -->
        <th:block th:replace="fragment/sidebar"/>
        <!-- BEGIN CONTENT -->
        <div class="page-content-wrapper">
            <!-- BEGIN CONTENT BODY -->
            <div class="page-content">
                <!-- BEGIN PAGE BAR -->
                <div class="page-bar">
                    <ul class="page-breadcrumb">
                        <li><a href="dashboard" class='msg_home'>控制台</a> <i class="fa fa-circle"></i></li>
                        <li><span class='msg_order_management'>订单管理</span></li>
                    </ul>
                </div>
                <!-- BEGIN main content -->
                <div class="row">
                    <!-- BEGIN ===========page level content============= -->
                    <div class="col-md-12">
                        <!--======== Instruction ========-->
                        <th:block th:replace="order/fragements/instructions"/>
                        <!-- BEGIN Error Message -->
                        <div class="alert alert-danger hidden" id="form_error_msg">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                            <strong class="msg_err_title"></strong>
                            <span class="msg_err_subTitle"> </span>
                        </div>
                        <!--======== Filter form ========-->
                        <div class="portlet light list_filter_form">
                            <div class="portlet-title">
                                <div class="caption">
                                    <i class="icon-equalizer font-red-sunglo"></i>
                                    <span class="caption-subject font-red-sunglo bold uppercase">筛选条件</span>
                                    <span class="caption-helper"></span>
                                </div>
                                <div class="tools">
                                    <a href="" class="collapse" data-original-title="" title=""> </a>
                                    <a href="" class="remove" data-original-title="" title=""> </a>
                                </div>
                            </div>
                            <div class="portlet-body form">
                                <table class="table table-striped table-bordered table-hover filterWidget">
                                    <thead>
                                    <tr role="row" class="heading">
                                        <th width="10%" class="msg_ent_fld_sys_trd_id">系统单号</th>
                                        <th width="10%" class="">平台单号</th>
                                        <th width="10%" class="msg_ent_fld_receiver">收件人姓名</th>
                                        <th width="15%" class="msg_ent_fld_phone">手机</th>
                                        <th width="15%" class="msg_ent_fld_address">地址</th>
                                        <th width="10%" class="msg_ent_fld_trd_status">状态</th>
                                        <th width="20%" class="msg_ent_fld_updateAt">更新日期</th>
                                        <th width="10%"  class="msg_action"> 操作</th>
                                    </tr>
                                    <tr role="row" class="filter">
                                        <td>
                                            <input name="id" type="text"
                                                   class="form-control form-filter input-sm">
                                        </td>
                                        <td>
                                            <input name="extTxnId" type="text"
                                                   class="form-control form-filter input-sm">
                                        </td>
                                        <td>
                                            <input name="receiver" data-operator='like' type="text"
                                                   class="form-control form-filter input-sm">
                                        </td>
                                        <td>
                                            <input name="phoneNum" type="text"
                                                   class="form-control form-filter input-sm">
                                        </td>
                                        <td>
                                            <input name="address" data-operator='like' type="text"
                                                   class="form-control form-filter input-sm">
                                        </td>
                                        <td>
                                            <select name="status" class="form-control form-filter input-sm">
                                                <option value=""></option>
                                                <option value="0" class="msg_order_std_0">待付款</option>
                                                <option value="10" class="msg_order_std_10">未确认</option>
                                                <option value="20" class="msg_order_std_20">新订单</option>
                                                <option value="60" class="msg_order_std_60">已包装</option>
                                                <option value="70" class="msg_order_std_70">待发货</option>
                                                <option value="80" class="msg_order_std_80">已发货</option>
                                                <option value="90" class="msg_order_std_90">已签收</option>
                                                <option value="95" class="msg_order_std_95">已结算</option>
                                                <option value="100" class="msg_order_std_100">交易关闭</option>
                                            </select>
                                        </td>
                                        <td>
                                            <div class="input-group input-large date-picker input-daterange"
                                                 data-date="10/11/2012"
                                                 data-date-format="yyyy-mm-dd">
                                                <input type="text" class="form-control"
                                                       name="updateAt_from" data-operator='between' placeholder="年-月-日">
                                                <span class="input-group-addon"> 至 </span>
                                                <input type="text" class="form-control"
                                                       name="updateAt_to" data-operator='between' placeholder="年-月-日">
                                            </div>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-success filter-submit margin-bottom"
                                                    id="btn_filter_search">
                                                <i class="fa fa-search"></i> 搜索
                                            </button>
                                            <button class="btn btn-sm btn-default filter-cancel"
                                                    id="btn_filter_reset">
                                                <i class="fa fa-times"></i> 重置
                                            </button>
                                        </td>
                                    </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>
                        <!--======== Data table ========-->
                        <div id="order_list_wrap" class="">
                            <div class="portlet box green datatable-portlet">
                            <div class="portlet-title">
                                <div class="caption">
                                    <i class="fa fa-list"></i><span class='msg_listTitle'>列表</span>
                                </div>
                                <div class="tools">
                                    <div th:if="${session.isSuperUser||
                                                        session.authStr.contains(importAuth)||
                                                        session.authStr.contains(exportAuth)}"
                                         class="btn-group">
                                        <a class="btn green" href="javascript:;"
                                           data-toggle="dropdown">
                                            <i class="fa fa-file-upload"></i>
                                        </a>
                                        <ul class="dropdown-menu pull-right">
                                            <th:block
                                                    th:if="${ session.isSuperUser|| session.authStr.contains(importAuth) }">
                                                <li>
                                                    <a href="importTrades">
                                                        <i class="fa fa-file-upload"></i> 批量导入 </a>
                                                </li>
                                                <li>
                                                    <a href="api/download/template/?filename=trade_order_orig.xlsx"
                                                       target="_blank"><i
                                                            class="fa fa-file-text"></i> 下载模版 </a>
                                                </li>
                                            </th:block>
                                            <li th:if="${ session.isSuperUser||session.authStr.contains(exportAuth)}">
                                                <a id="btn_batch_export"> <i
                                                        class="fa fa-file-download"></i> 批量导出</a>
                                            </li>
                                        </ul>
                                    </div>

                                    <button th:if="${ session.isSuperUser||session.authStr.contains(createAuth)}"
                                            id="btn_add_entity" class="btn sbold green" title="创建订单">
                                        <i class="fa fa-plus"></i>
                                    </button>
                                    <button th:if="${ session.isSuperUser||session.authStr.contains(deleteAuth)}"
                                            id="btn_del_entity" class="btn sbold green" title="删除">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                    <button th:if="${ session.isSuperUser||session.authStr.contains(createAuth)}"
                                            id="btn_sync_orders" class="btn sbold green" title="同步数据">
                                        <i class="fas fa-link"></i>
                                    </button>
                                    <button id="btn_refresh_dt" class="btn sbold green" title="刷新">
                                        <i class="fas fa-sync"></i>
                                    </button>
                                    <div class="btn-group">
                                        <a class="btn btn-sm green" href="javascript:;" data-toggle="dropdown"
                                           title="工具">
                                            <i class="fa fa-tools"></i>
                                        </a>
                                        <ul class="dropdown-menu pull-right" role="menu">
                                            <li>
                                                <a href="javascript:;" id="btn_toggle_calc" class="">
                                                    <i class="fas fa-calculator"></i>
                                                    计算器
                                                </a>
                                            </li>
                                        </ul>
                                    </div>
                                    <div th:if="${ session.isSuperUser||session.authStr.contains(authTarget + '_' + ERPConstants.AUTH_ACTVT_SUBMIT)||
                                                                        session.isSuperUser||session.authStr.contains(packingAuth)||
                                                                        session.isSuperUser||session.authStr.contains(deliverAuth)||
                                                                        session.isSuperUser||session.authStr.contains(signoffAuth)||
                                                                        session.isSuperUser||session.authStr.contains(settleAuth)||
                                                                        session.isSuperUser||session.authStr.contains(closeAuth)}"
                                         class="btn-group">
                                        <a class="btn btn-sm green" href="javascript:;" data-toggle="dropdown"
                                           title="更新状态">
                                            <i class="fas fa-tasks"></i>
                                        </a>
                                        <th:block th:replace="order/fragements/orderActions"/>
                                    </div>
                                </div>
                            </div>
                            <div class="portlet-body">
                                <table class="table table-striped table-bordered table-hover dt-responsive"
                                       width="100%" id="dt_trade" cellspacing="0">
                                    <thead>
                                    <tr>
                                        <th width="2%">
                                            <label
                                                    class="mt-checkbox mt-checkbox-single mt-checkbox-outline">
                                                <input type="checkbox" class="group-checkable"
                                                       data-set="#dt_trade .checkboxes"/>
                                                <span></span>
                                            </label></th>
                                        <th width='' class='msg_ent_fld_sys_trd_id'></th>
                                        <th width='' class='msg_ent_fld_receiver'></th>
                                        <th width='' class='msg_ent_fld_phone'></th>
                                        <th width='' class='msg_ent_fld_address'></th>
                                        <th width='' class='msg_ent_fld_expressName'></th>
                                        <th width='' class='msg_ent_fld_expressOrderId'></th>
                                        <th width='' class='msg_ent_fld_trd_status'></th>
                                        <th width='' class='msg_ent_fld_updateAt'></th>
                                        <!--<th width="2%"></th>-->
                                    </tr>
                                    </thead>
                                </table>
                            </div>
                        </div>
                        </div>
                        <!--======== Summary form ========-->
                        <div id="order_summary_wrap"  class="hidden">
                            <div id="calcPortlet" class="portlet light list_filter_form ">
                            <div class="portlet-title">
                                <div class="caption">
                                    <i class="fa fa-list-alt font-red-sunglo"></i>
                                    <span class="caption-subject font-red-sunglo bold uppercase">订单合计</span>
                                    <span class="caption-helper"></span>
                                </div>
                                <div class="tools">
                                    <a href="" class="collapse" data-original-title="" title=""> </a>
                                    <a href="" class="btn_remove_caryr" data-original-title="" title=""> </a>
                                </div>
                            </div>
                            <div class="portlet-body form">
                                <form action="#" id="trade_import_summary_form" class="horizontal-form">
                                    <div id="summary_pro_list" class="row list_tail" >
                                        <p class="col-md-9">&nbsp;</p>
                                        <p class="col-md-3">&nbsp;</p>
                                    </div>
                                    <div class="row list_tail">
                                        <p class="col-md-9">订单总数</p>
                                        <p id="summary_order_count" class="col-md-2 text-right">0</p>
                                    </div>
                                    <div class="row list_tail">
                                        <p class="col-md-9">总金额</p>
                                        <p id="summary_total_amt" class="col-md-2 text-right">0</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        </div>
                    </div>
                    <!-- END ===========page level content============= -->
                </div>
            </div>
        </div>
    </div>

    <th:block th:replace="fragment/rear"/>
    <!-- BEGIN Page level plugins -->
    <script src="resources/assets/global/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
    <script src="resources/assets/global/plugins/datatables/datatables.min.js"></script>
    <script src="resources/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js"></script>
    <script src="resources/assets/caryr/caryr.datatable.js"></script>
    <!-- END Page level plugins -->
</th:block>
<script th:inline="javascript">
    jQuery(document).ready(function () {

        /*[+
        caryr.lang = [[${session.lang}]];
        var createAuth = ('true'==[[${session.isSuperUser||session.authStr.contains(createAuth)?'true':'false'}]]);
        var updateAuth = ('true'==[[${session.isSuperUser||session.authStr.contains(updateAuth)?'true':'false'}]]);
        var disableModify = ('true'==[[${session.isSuperUser||session.authStr.contains(updateAuth)?'false':'true'}]]);
        +]*/

        var tableId = '#dt_trade';
        $('.date-picker').datepicker({autoclose: true});
        /***************** Filter Widget **************/
        $('#btn_filter_reset').on('click', function () {
            caryr.updateEntity($(this).closest('.filterWidget'), {});
        });

        $('#btn_filter_search').on('click', function () {
            var entity = caryr.collectEntity($(".filterWidget"), {
                nonNull: true,
                isFilter: true
            });
            dataTable.search(caryr.toJson(entity)).draw();
        });

        /***************** Data Table **************/
        var dataTable = caryr.dataTable.create({
            url: "api/order",
            defaultOrderBy: 7,
            defaultOrderByDir: "asc",
            tableId: tableId,
            lang: caryr.lang,
            disableView: true,
            columns: [
                {
                    data: 'id', render: function (id) {
                        return "<a href='orderDetails?orderId=" + id + "' target='_blank'>" + id + "</a>";
                    }
                },
                {data: 'receiver'},
                {data: 'phoneNum'},
                {data: 'address'},
                {data: 'logisticsName'},
                {data: 'logisticsOrderId'},
                {data: 'status', render: caryr.order.orderStatusHtml},
                {data: 'updateAt'}
            ],
            checkEvent: function () {
                refreshSummaryEvent();
            },
            checkAllEvent: function () {
                refreshSummaryEvent();
            }
        });

        $('#btn_add_entity').on('click', function () {  //attach create trade
            window.location.href = "orderDetails?orderId=";
        });

        $('#btn_batch_export').on('click', function () {
            var selectData = dataTable.rows('.selected').data();
            if (selectData.length == 0) {
                swal($.i18n.prop("msg_com_noDataSelect"), "", "error");
                return;
            }
            //collect selected Id
            var ids = '';

            for (var i = 0; i < selectData.length; i++) {
                if (i == selectData.length - 1) {
                    ids += selectData[i].id;
                } else {
                    ids += selectData[i].id + ',';
                }
            }
            window.location.href = "api/download/orders/" + ids;
        });

        $('#btn_batch_update li a').on("click", function () {
            //check selected row
            var selectData = dataTable.rows('.selected').data();
            if (selectData.length == 0) {
                swal($.i18n.prop("msg_com_noDataSelect"), "", "error");
                return;
            }

            var nextStatus = $(this).attr('data-next-status');
            //collect selected Id
            var ids = new Array();
            var status;
            var valid = true;
            selectData.each(function (e, i) {
                if (!status) {
                    status = e.status;
                } else if (status != e.status) {
                    swal("订单状态不一致，请选择状态相同的订单", "", "error");
                    valid = false;
                    return false;
                }
                if (e.status >= nextStatus) {
                    swal("订单状态不符合操作，请重新选择订单", "", "error");
                    valid = false;
                    return false;
                }
                ids.push(e.id);
            });

            if (!valid) {
                return;
            }
            var data = {
                ids: ids,
                updateStatus: nextStatus
            };
            batchUpdate({
                data: data,
                url: 'api/order/batch',
                success: function () {
                    dataTable.draw();
                },
                error: function () {
                    dataTable.draw();
                }
            });
        });

        $('#btn_sync_orders').on('click', function () {
            caryr.ajaxReq({
                url: "api/order/syncOrder/",
                type: "POST",
                successMsgRender: function (response) {
                    var count = response && response.data && response.data.length ? response.data.length : 0;
                    return $.i18n.prop("msg_api_succ_update_count", count);
                },
                success: function () {
                    dataTable.draw();
                }
            });
        });

        $('#btn_toggle_calc').on('click', function () {
            toggleCalculator(false);
        });

        $('#order_summary_wrap a.btn_remove_caryr').on('click', function () {
            toggleCalculator(true);
        });

        /***************** Functions **************/
        function toggleCalculator(hidden) {
            if (hidden) {
                $('#order_list_wrap').removeClass('column-left');
                $('#order_list_wrap').removeClass('col-md-8');
                $('#order_summary_wrap').removeClass('column-right');
                $('#order_summary_wrap').removeClass('col-md-4');
                $('#order_summary_wrap').addClass('hidden');
            } else {
                $('#order_list_wrap').addClass('column-left');
                $('#order_list_wrap').addClass('col-md-8');
                $('#order_summary_wrap').addClass('column-right');
                $('#order_summary_wrap').addClass('col-md-4');
                $('#order_summary_wrap').removeClass('hidden');
            }
        }

        function summaryItemHtml(text, value, option) {
            var rowClass = option && option.rowClass ? option.rowClass : '';
            var html = '<div class="row ' + rowClass + '">' +
                '<p class="col-md-9">' + text + '</p>' +
                '<p class="col-md-2 text-right">' + value + '</p>' +
                '</div>';
            return html;
        }

        function refreshSummaryEvent() {
            //---- If calculator is hidden then return
            if ($('#order_summary_wrap').hasClass('hidden')) {
                return;
            }
            var idList = caryr.dataTable.selectedIds(dataTable, {emptyCheck: false});
            if (idList.length == 0) {
                refreshSummaryForm([]);
                return;
            }
            var ids = caryr.ids2UrlParam(idList);
            var filter = caryr.encodeUrlParam('search[value]', '{"id":{"value":"' + ids + '","operator":"in"}}');
            filter += '&loadDetail=true';
            filter += '&size=-1';
            var url = "api/order?" + filter;
            caryr.ajaxReq({
                url: url,
                type: "GET",
                skipMsg: true,
                success: function (response) {
                    refreshSummaryForm(response && response.data ? response.data : []);
                }
            });
        }

        function refreshSummaryForm(entities) {
            //--------------- Clear summary form
            var form = $('#trade_import_summary_form');
            form.find('.sum_status_order').remove();
            form.find('.sum_product').remove();
            var sumTotalAmt = form.find('#summary_total_amt');
            var sumOrderCount = form.find('#summary_order_count');
            var sumProList = form.find('#summary_pro_list');

            //--------------- Draw summary
            var totalAmount = 0, orderStatus = {}, productCountMap ={};
            for (var i = 0; i < entities.length; i++) {
                var order = entities[i];
                orderStatus[order.status] = orderStatus[order.status] ? orderStatus[order.status] + 1 : 1;
                totalAmount += order.orderAmount;
                if (order.tradeOrderList) {
                    for (var j = 0; j < order.tradeOrderList.length; j++) {
                        var orderItem = order.tradeOrderList[j];
                        var productSpecAmount = parseFloat(orderItem.productSpecAmount);
                        if (!productCountMap[orderItem.productSpecId]) {
                            productCountMap[orderItem.productSpecId] = {
                                count: productSpecAmount,
                                name: orderItem.name
                            };
                        } else {
                            productCountMap[orderItem.productSpecId].count = productCountMap[orderItem.productSpecId].count + productSpecAmount;
                        }
                    }
                }
            }
            //--------------- Summary Product list
            for (var productId in productCountMap) {
                if (productCountMap.hasOwnProperty(productId)) {
                    var productCount = productCountMap[productId];
                    var html = summaryItemHtml(productCount.name, productCount.count, {rowClass: 'sum_product'});
                    sumProList.closest('.row').before(html);
                }
            }
            //--------------- Summary Order Status list
            for (var status in orderStatus) {
                if (orderStatus.hasOwnProperty(status)) {
                    var txt = caryr.order.orderStatusHtml(status);
                    var html = summaryItemHtml(txt, orderStatus[status], {rowClass: 'sum_status_order'});
                    sumOrderCount.closest('.row').before(html);
                }
            }
            sumOrderCount.html(entities.length);
            sumTotalAmt.html(totalAmount);
        }

        function batchUpdate(option) {
            var url = option.url;
            var ids = option.ids;

            swal({
                title: $.i18n.prop("msg_com_confirmModify"),
                confirmButtonText: $.i18n.prop("msg_com_formOK"),
                cancelButtonText: $.i18n.prop("msg_com_formCancel"),
                text: "",
                type: "info",
                showCancelButton: true,
                closeOnConfirm: false,
                showLoaderOnConfirm: true
            }, function () {
                $.ajax({
                    type: "POST",
                    url: url,
                    traditional: true, //参数序列化的传统样式
                    data: option.data,
                    success: function (data) {
                        var msgTxt = $.i18n.prop("msg_api_succ_update");
                        swal({
                            title: msgTxt,
                            text: "",
                            type: "success"
                        }, function () {
                            if (option.success) {
                                option.success();
                            }
                        });
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        var msgTxt = "";
                        if (XMLHttpRequest && XMLHttpRequest.responseJSON) {
                            msgTxt = $.i18n.prop("msg_err_" + XMLHttpRequest.responseJSON.code);
                        }
                        var reg = /^\[.*\]$/;
                        if (reg.test(msgTxt)) {
                            msgTxt = $.i18n.prop("msg_com_systemError");
                        }
                        swal({
                            title: msgTxt,
                            text: "",
                            type: "error"
                        }, function () {
                            if (option.error) {
                                option.error();
                            }
                        });
                    }
                });
            });
        }
    });
</script>
</body>
</html>